<?php
namespace Modules\Taxonomy\Forms;

class ElementHook
{
    public static function tagTermSetDefault($params)
    {
        $di = \Phalcon\Di::getDefault();
        $value = $params['value'];
        $output = [];
        if (is_string($value)) {
            $value = explode(',', $value);
        }
        $termData = $di->getShared('entityManager')->find('term', [
            'conditions' => [
                'id' => [
                    '$in' => $value
                ]
            ]
        ]);
        foreach ($termData as $term) {
            $output[$term->id] = $term->name;
        }
        return $output;
    }

    public static function tagTermGetValue($params)
    {
        $di = \Phalcon\Di::getDefault();
        $options = $params['options'];
        $value = $params['value'];
        $output = [];
        if (is_string($value)) {
            $value = explode(',', $value);
        }
        $termData = $di->getShared('entityManager')->find('term', [
            'conditions' => [
                'contentModel' => $options['taxonomy'],
                'name' => [
                    '$in' => $value
                ]
            ]
        ]);
        foreach ($termData as $term) {
            $termKey = array_search($term->name, $value);
            if ($termKey !== false) {
                unset($value[$termKey]);
            }
            $output[$term->id] = $term->id;
        }
        foreach ($value as $term) {
            $termEntity = $di->getShared('entityManager')->get('term');
            $termEntity->name = $term;
            $termEntity->description = $term;
            if ($termEntity->save()) {
                $output[$termEntity->getId()] = $termEntity->getId();
            }
        }
        return $output;
    }
}